package mao.thinkinjava.concurency.atomic;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author Totoro
 * @date 2020/5/9 14:18
 *并发问题就是数据处于中间状态。
 */
public class AtomicTest  implements Runnable {
    private AtomicInteger value = new AtomicInteger(0);
    private int i=0;


    public int  evenAddThreadSafe() {
        while ( !value.compareAndSet(value.get(), value.get()+2));
        //value.compareAndSet(value.get(), value.get()+2);
        System.out.println(value.get());
        return value.get();
    }
    public void evenAdd(){
        i++;
        i++;
    }

    public int getI() {
        return i;
    }

    public int getValue() {
        return value.get();
    }

    @Override
    public void run() {
         while (true){
             evenAddThreadSafe();
         }

    }

    public static void main(String[] args) {
        ExecutorService exe = Executors.newCachedThreadPool();
        AtomicTest at = new AtomicTest();
        System.out.println("start....");
        exe.execute(at);
        exe.execute(at);
        exe.execute(at);
        //定时任务
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("aborting");
                System.out.flush();
                System.exit(0);
            }
        },500);

        while (true){
            int i = at.getValue();
            if(i%2 != 0){
                System.out.println("error occurs");
                System.exit(0);
            }
        }

    }
}
